package com.xu.tools.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xuguan
 * @date 2023/2/8
 * @desc 日期工具类
 */
public class DateUtil {

    public static final String FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static Date now() {
        return new Date();
    }

    public static String formatDate(Date date) {
        return formatDate(date, FORMAT_PATTERN);
    }

    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static Date parseDate(String str) {
        return parseDate(str, FORMAT_PATTERN);
    }

    public static Date parseDate(String str, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    public static Date addDate(Date sourceDate, long count, TimeUnit timeUnit) {
        long millions = sourceDate.getTime() + timeUnit.toMillis(count);
        return new Date(millions);
    }

    public static Date subDate(Date sourceDate, long count, TimeUnit timeUnit) {
        long millions = sourceDate.getTime() - timeUnit.toMillis(count);
        return new Date(millions);
    }

    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("formatDate(date) = " + formatDate(date));
        Date targetDate = addDate(date, 10, TimeUnit.MINUTES);
        System.out.println("formatDate(targetDate) = " + formatDate(targetDate));
    }
}
